SELECT
    Series.ID SeriesID,
    CONVERT(VARCHAR(200), Series.ID) SeriesKey,
    Channel.Name ChannelName,
    AlarmRangeLimit.High,
    AlarmRangeLimit.Low
INTO #channelMap
FROM
    AlarmRangeLimit JOIN
    Channel ON AlarmRangeLimit.ChannelID = Channel.ID JOIN
    Series ON Series.ChannelID = Channel.ID JOIN
    SeriesType ON
        Series.SeriesTypeID = SeriesType.ID AND
        SeriesType.Name = 'Average'
WHERE AlarmRangeLimit.RangeInclusive = 0
GO

INSERT INTO AlarmGroup(Name, AlarmTypeID, SeverityID)
SELECT
    #channelMap.SeriesKey Name,
    AlarmType.ID AlarmTypeID,
    AlarmSeverity.ID SeverityID
FROM
    #channelMap JOIN
    AlarmType ON AlarmType.Name IN ('Upper Limit', 'Lower Limit') JOIN
    AlarmSeverity ON AlarmSeverity.Name = 'Alert'
GO

INSERT INTO Alarm(AlarmGroupID, SeriesID)
SELECT AlarmGroup.ID AlarmGroupID, #channelMap.SeriesID
FROM
    #channelMap JOIN
    AlarmGroup ON AlarmGroup.Name = #channelMap.SeriesKey
GO

INSERT INTO AlarmValue(AlarmID, Value, StartHour, EndHour, Formula)
SELECT
    Alarm.ID AlarmID,
    CASE
        WHEN AlarmType.Name = 'Upper Limit' THEN #channelMap.High
        WHEN AlarmType.Name = 'Lower Limit' THEN #channelMap.Low
    END Value,
    0 AS StartHour,
    24 AS EndHour,
    '' Formula
FROM
    #channelMap JOIN
    AlarmGroup ON AlarmGroup.Name = #channelMap.SeriesKey JOIN
    Alarm ON Alarm.AlarmGroupID = AlarmGroup.ID JOIN
    AlarmType ON
        AlarmGroup.AlarmTypeID = AlarmType.ID AND
        AlarmType.Name IN ('Upper Limit', 'Lower Limit')
GO

UPDATE AlarmGroup
SET Name = CONCAT(#channelMap.ChannelName, ' ', AlarmType.Name)
FROM
    AlarmGroup JOIN
    #channelMap ON AlarmGroup.Name = #channelMap.SeriesKey JOIN
    AlarmType ON
        AlarmGroup.AlarmTypeID = AlarmType.ID AND
        AlarmType.Name IN ('Upper Limit', 'Lower Limit')
GO